<?php
//搜索类
class lib_search{
	private $model;
	
	private $fields,$keywords;
	
	private $order_by,$order_by_direction,$limit,$offset;
	
	public static function instance($model){
		if (!is_string($model)){
			return false;
		}
		$_instance = new self;
		$_instance->model = MYSQL::factory($model);
		return $_instance;
	}
	
	public function in($fields){
		if (!is_array($fields)){
			$fields = func_get_args();
		}
		$this->fields = $fields;
		return $this;
	}
	
	public function find($keywords){
		$keywords = explode(' ',$keywords);
		$this->keywords = '%'.implode('%',$keywords).'%';
		return $this;
	}
	
	public function order_by($fields,$direction = 'asc'){
		$this->order_by = $fields;
		$this->order_by_direction = $direction;
		return $this;
	}
	
	public function limit($max){
		$this->limit = $max;
		return $this;
	}
	
	public function offset($start){
		$this->offset = $start;
		return $this;
	}
	
	public function num_rows(){
		if (!isset($this->keywords)) return false;
		foreach ($this->fields as $field){
			$this->model->or_where($field,'like',$this->keywords);
		}
		return $this->model->num_rows();
	}
	
	public function exec(){
		if (!isset($this->keywords)) return false;
		foreach ($this->fields as $field){
			$this->model->or_where($field,'like',$this->keywords);
		}
		if (isset($this->offset)) $this->model->offset($this->offset);
		if (isset($this->limit)) $this->model->limit($this->limit);
		if (isset($this->order_by) && isset($this->order_by_direction))
			$this->model->order_by($this->order_by,$this->order_by_direction);
		
		return $this->model->select()->exec();
	}
}